﻿using Common.Class;
using Common.Model;
using Microsoft.VisualBasic.ApplicationServices;
using SyncFileCommon.BLL;

namespace RdpClient.BLL
{
    public class ServerBLL
    {

        /// <summary>
        /// 服务器令牌
        /// </summary>
        private static string _ServerTokenID = "";

        /// <summary>
        /// 服务器通讯加密Key
        /// </summary>
        private static string _AesKey = "";


        public static string TokenIDGet()
        {
            //获取服务器会话列表
            if (string.IsNullOrWhiteSpace(_ServerTokenID))
            {
                string _result = WebApiHelper.RunWebApiService(EncryptHelper.DecryptString_Aes(ConfigBLL.ServiceConfig.ServiceURL, "JlPwd") + "/api/User/TokenIDGet", null);
                if (string.IsNullOrWhiteSpace(_result))
                {

                }
                else
                {
                    ServiceResultModel _serviceResult = JsonHelper.GetObjectFromJsonStr<ServiceResultModel>(_result);
                    if (_serviceResult.Success == 1)
                    {
                        dynamic _data = JsonHelper.JsonToDynamic(Convert.ToString(_serviceResult.Result));
                        _ServerTokenID = _data.TokenID;
                    }
                }

            }

            return _ServerTokenID;
        }

        /// <summary>
        /// 初始化通讯加密Key
        /// </summary>
        /// <returns></returns>
        public static bool AesKeyInit()
        {
            string _paramStr = new JsonHelper()
                .JsonStr;
            string _result = WebApiHelper.RunWebApiService(EncryptHelper.DecryptString_Aes(ConfigBLL.ServiceConfig.ServiceURL, "JlPwd") + "/api/User/RandomKeyGet", new Dictionary<string, string>() { { "TokenID", TokenIDGet() }, { "ParamStr", _paramStr } });
            if (string.IsNullOrWhiteSpace(_result))
            {
                _AesKey = "";
            }
            else
            {
                ServiceResultModel _serviceResult = JsonHelper.GetObjectFromJsonStr<ServiceResultModel>(_result);
                if (_serviceResult.Success == 1)
                {
                    dynamic _data = JsonHelper.JsonToDynamic(Convert.ToString(_serviceResult.Result));
                    string _randomKey = _data.RandomKey;
                    if (!string.IsNullOrWhiteSpace(_randomKey))
                    {
                        string _guid = (Guid.NewGuid().ToString().Replace("-", ""));
                        string _aesKey = _randomKey + _guid.Substring(0, 32 - _randomKey.Length);

                        _paramStr = new JsonHelper()
                            .AddVar("Key", EncryptHelper.EncryptString_RSA(_aesKey, StringHelper.Decompress(EncryptHelper.DecryptString_Aes(ConfigBLL.ServiceConfig.ServicePublicKey, "JlPwd"))))
                            .JsonStr; ;
                        _result = WebApiHelper.RunWebApiService(EncryptHelper.DecryptString_Aes(ConfigBLL.ServiceConfig.ServiceURL, "JlPwd") + "/api/User/ClientKey", new Dictionary<string, string>() { { "TokenID", TokenIDGet() }, { "ParamStr", _paramStr } });
                        if (string.IsNullOrWhiteSpace(_result))
                        {
                            _AesKey = "";
                        }
                        else
                        {
                            _serviceResult = JsonHelper.GetObjectFromJsonStr<ServiceResultModel>(_result);
                            if (_serviceResult.Success == 1)
                            {
                                _AesKey = _aesKey;
                                return true;
                            }
                        }


                    }


                }
            }
            return false;
        }

        /// <summary>
        /// 判断用户是否已经登录
        /// </summary>
        /// <returns></returns>
        public static int IsLogin()
        {
            string _paramStr = new JsonHelper()
               .JsonStr;
            string _result = WebApiHelper.RunWebApiService(EncryptHelper.DecryptString_Aes(ConfigBLL.ServiceConfig.ServiceURL, "JlPwd") + "/api/User/IsLogin", new Dictionary<string, string>() { { "TokenID", TokenIDGet() }, { "ParamStr", _paramStr } });
            if (string.IsNullOrWhiteSpace(_result))
            {
                return -1;
            }
            else
            {
                ServiceResultModel _serviceResult = JsonHelper.GetObjectFromJsonStr<ServiceResultModel>(_result);
                if (_serviceResult.Success == 1)
                {
                    //已登录
                    return 1;
                }
                else if (_serviceResult.Success == -999)
                {
                    //加密Key过期，重新设置加密KEY
                    if (AesKeyInit())
                    {
                        return IsLogin();
                    }
                }
                else if (_serviceResult.Success == 0)
                {
                    //没登录
                    return 0;
                }
            }

            return 0;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userID">登录名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public static bool UserLogin(string userID, string password)
        {

            string _paramStr = new JsonHelper()
                .AddVar("UserID", userID)
                .AddVar("Password", password)
               .JsonStr;
            string _result = WebApiHelper.RunWebApiService(
                EncryptHelper.DecryptString_Aes(ConfigBLL.ServiceConfig.ServiceURL, "JlPwd") + "/api/User/ClientLogin",
                    new Dictionary<string, string>() {
                        { "TokenID", TokenIDGet() },
                        { "ParamStr", EncryptHelper.EncryptString_Aes(_paramStr, _AesKey) } });
            if (string.IsNullOrWhiteSpace(_result))
            {
                return false;
            }
            else
            {
                ServiceResultModel _serviceResult = JsonHelper.GetObjectFromJsonStr<ServiceResultModel>(_result);
                if (_serviceResult.Success == 1)
                {
                    //登录成功
                    return true;
                }
                else if (_serviceResult.Success == -999)
                {
                    //加密Key过期，重新设置加密KEY
                    if (AesKeyInit())
                    {
                        return UserLogin(userID, password);
                    }
                }
                else if (_serviceResult.Success == 0)
                {
                    //没登录
                    return false;
                }
            }

            return false;
        }

        /// <summary>
        /// 获取用户会话列表
        /// </summary>
        /// <returns></returns>
        public static List<SessionModel> UserSessionListGet()
        {
            string _result = WebApiHelper.RunWebApiService(
                EncryptHelper.DecryptString_Aes(ConfigBLL.ServiceConfig.ServiceURL, "JlPwd") + "/api/User/UserSessionListGet", new Dictionary<string, string>() { { "TokenID", TokenIDGet() } });
            if (string.IsNullOrWhiteSpace(_result))
            {
                return null;
            }
            else
            {
                ServiceResultModel _serviceResult = JsonHelper.GetObjectFromJsonStr<ServiceResultModel>(_result);
                if (_serviceResult.Success == 1)
                {
                    JsonHelper _json = new JsonHelper(EncryptHelper.DecryptString_Aes(Convert.ToString(_serviceResult.Result), _AesKey));
                    List<SessionModel> _sessionList = JsonHelper.GetObjectFromJsonStr<List<SessionModel>>(_json.GetVar("SessionList"));
                    return _sessionList;
                }
                else if (_serviceResult.Success == -999)
                {
                    //加密Key过期，重新设置加密KEY
                    if (AesKeyInit())
                    {
                        return UserSessionListGet();
                    }
                }
                else if (_serviceResult.Success == 0)
                {
                    //没登录
                    return null;
                }
            }

            return null;
        }

        /// <summary>
        /// 获取会话信息
        /// </summary>
        /// <param name="sessionID">会话ID</param>
        /// <returns></returns>
        public static SessionModel UserSessionGetFromID(long sessionID)
        {
            string _paramStr = new JsonHelper()
                .AddVar("SessionID", Convert.ToString(sessionID))
                .JsonStr;
            string _result = WebApiHelper.RunWebApiService(
                EncryptHelper.DecryptString_Aes(ConfigBLL.ServiceConfig.ServiceURL, "JlPwd") + "/api/User/UserSessionGetFromID", new Dictionary<string, string>() {
                        { "TokenID", TokenIDGet() },
                        { "ParamStr", EncryptHelper.EncryptString_Aes(_paramStr, _AesKey) } });
            if (string.IsNullOrWhiteSpace(_result))
            {
                return null;
            }
            else
            {
                ServiceResultModel _serviceResult = JsonHelper.GetObjectFromJsonStr<ServiceResultModel>(_result);
                if (_serviceResult.Success == 1)
                {
                    JsonHelper _json = new JsonHelper(EncryptHelper.DecryptString_Aes(Convert.ToString(_serviceResult.Result), _AesKey));
                    SessionModel _session = JsonHelper.GetObjectFromJsonStr<SessionModel>(_json.GetVar("Session"));
                    return _session;
                }
                else if (_serviceResult.Success == -999)
                {
                    //加密Key过期，重新设置加密KEY
                    if (AesKeyInit())
                    {
                        return UserSessionGetFromID(sessionID);
                    }
                }
                else if (_serviceResult.Success == 0)
                {
                    return null;
                }
            }

            return null;
        }

        /// <summary>
        /// 修改操作员登录密码
        /// </summary>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public static bool UserChangePassword(string oldPassword, string newPassword)
        {
            string _paramStr = new JsonHelper()
                .AddVar("OldPassword", oldPassword)
                .AddVar("NewPassword", newPassword)
                .JsonStr;
            string _result = WebApiHelper.RunWebApiService(
                EncryptHelper.DecryptString_Aes(ConfigBLL.ServiceConfig.ServiceURL, "JlPwd") + "/api/User/ClientUserChangePassword", new Dictionary<string, string>() {
                        { "TokenID", TokenIDGet() },
                        { "ParamStr", EncryptHelper.EncryptString_Aes(_paramStr, _AesKey) } });
            if (string.IsNullOrWhiteSpace(_result))
            {
                return false;
            }
            else
            {
                ServiceResultModel _serviceResult = JsonHelper.GetObjectFromJsonStr<ServiceResultModel>(_result);
                if (_serviceResult.Success == 1)
                {
                    return true;
                }
                else if (_serviceResult.Success == -999)
                {
                    //加密Key过期，重新设置加密KEY
                    if (AesKeyInit())
                    {
                        return UserChangePassword(oldPassword, newPassword);
                    }
                }
                else if (_serviceResult.Success == 0)
                {
                    return false;
                }
            }

            return false;
        }

    }
}
